import redis
import threading
import random, time
import sys, getopt

class KeyGenerator:
    def __init__(self):
        self.token = "0123456789abcdefghijklmnopqrstuvwxyz"
        
    def next(self):
        result = ""
        for i in range(10):
            result += self.token[int(random.uniform(0, 36))]
        return result



class RedisConnection(threading.Thread):
    def __init__(self, server, requests_per_pipeline):
        threading.Thread.__init__(self)
        self.redis_server = redis.Redis(host=server, port=6379)
        self.requests_per_pipeline = requests_per_pipeline
        self.number_of_requests = 0
        self.thread_stop = False

    def run(self):
    	key_generator = KeyGenerator()
        content = "a" * 50
        while not self.thread_stop:
            current_pipeline = self.redis_server.pipeline()
            for j in range(self.requests_per_pipeline):
                current_key = key_generator.next()
                current_pipeline.set(current_key, content)
                current_pipeline.get(current_key)
            current_pipeline.execute()
            self.number_of_requests += self.requests_per_pipeline * 2
        self.redis_server.save()

    def stop(self):  
        self.thread_stop = True 



def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "c:r:t:")
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)

    # set default value
    clients = 1
    requests = 10
    test_time = 60
    host = "localhost"

    for o, s in opts:
        if o == "-c":
            clients = int(s)
        elif o == "-r":
            requests = int(s)
        elif o == "-t":
            test_time = int(s)

    # send requst by giving frequency
    connections = []
    for i in range(clients):
        connection = RedisConnection(server=host, requests_per_pipeline=requests)
        connection.start()
        connections.append(connection)
    
    time.sleep(test_time-1)
    number_of_requests = 0
    for i in range(clients):
        connections[i].stop()
        connections[i].join()
        number_of_requests += connections[i].number_of_requests
    print "Test time\tNumber of requests\tAverage request per second"
    print str(test_time) + "\t\t" + str(number_of_requests) + "\t\t\t" + str(number_of_requests/test_time)


if __name__ == "__main__":
    main(sys.argv)